const path = require('path');
const fs = require('fs');

const ejs = require('ejs');


const compile = (templateName, data) => {
  const templatePosition = `../templates/${templateName}`;
  const templatePath = path.resolve(__dirname, templatePosition);
  // 这里使用promise是为了将renderFile中回调函数生成的result取出
  return new Promise((resolve, reject) => {
    // 固定用法，renderFile会编译ejs文件，输出结果
    ejs.renderFile(templatePath, { data }, {}, (err, result) => {
      if (err) {
        console.log(err);
        reject(err);
        return;
      }
      resolve(result);
    })
  })
}

// source/components/category/why
// 递归创建文件夹
const createDirSync = (pathName) => {
  if (fs.existsSync(pathName)) {
    return true;
  } else {
    if (createDirSync(path.dirname(pathName))) {
      fs.mkdirSync(pathName);
      return true;
    }
  }
}


const writeToFile = (targetPath, content, extName = null) => {
  console.log(extName);
  // 判断path是否存在, 如果不存在, 创建对应的文件夹
  const dirPath = path.resolve(path.dirname(targetPath), path.basename(targetPath, '.js'));
  const finalName = path.resolve(dirPath, extName);
  if (extName === 'index.js') {
      fs.mkdirSync(dirPath);
      return fs.promises.writeFile(finalName, content)
  } else if(extName === 'style.js') {
    return fs.promises.writeFile(finalName, content)
  }
  return fs.promises.writeFile(targetPath, content);
}

module.exports = {
  compile,
  writeToFile,
  createDirSync
}

